/*
 * @Author: jiaxiuc
 * @Date: 2024-12-12 09:34:17
 * @LastEditors: jiaxiuc
 * @LastEditTime: 2025-01-16 17:14:03
 */
function random(min, max) {
  return Math.floor(Math.random() * (max - min + 1) + min);
}
const utils = {
  sleep(time) {
    return new Promise((resolve) => {
      setTimeout(() => {
        resolve();
      }, time);
    });
  },
  async startMatch(data) {
    const userList = [];
    let list1 = this.matchDom(data);
    userList.push(...list1);
    /*匹配第二页 START*/
    // const pages = $('#b_results .b_pag .sb_pagF li');
    // console.log('分页：', pages.length);
    // if (pages.length) {
    //   pages.eq(1).find('a').click();
    //   while ($('#b_results .b_pag .sb_pagF li').length) {
    //     await this.sleep(200);
    //   }
    //   let list2 = this.matchDom(data);
    //   userList.push(...list2);
    // }
    /*匹配第二页 END*/
    console.log('匹配结果：', data, userList);
    //上报结果 START
    chrome.runtime.sendMessage({ type: 'searchsuccess', data: userList, from: 'biying' }, function (response) {
      if (response?.action == 'search') {
        const company = response.data.company;
        const name = response.data.name;
        // setTimeout(() => {
        //   $('#sb_form_q').get(0).value = `${company} ${name}`;
        // },random(100, 300));
        // setTimeout(() => {
        //   $('#sb_form').get(0).submit();
        // },random(500, 800));
        setTimeout(() => {
          window.location.replace(`/search?q=${encodeURIComponent(company + ' ' + name)}`);
        }, random(200, 500));
      } else if (response?.action == 'over') {
        console.info('搜索已完成，关闭窗口');
        chrome.runtime.sendMessage({ type: 'closetab', from: 'biying' });
      }
    });
    // console.log('匹配结果匹配结果：', user);
  },
  matchDom(data) {
    var userList = [];
    const container = $('#b_results .b_algo');
    for (let i = 0; i < container.length; i++) {
      // if ($(container[i]).hasClass('middle-better-hintBox')) {
      //   continue;
      // }
      const text = ($(container[i]).find('h2 a').text() + $(container[i]).find('.b_lineclamp2').text()).replaceAll(/\s/g, '');
      const idx1 = text.indexOf(data?.company);
      const idx2 = text.indexOf(data?.name);
      if (idx1 == -1 || idx2 == -1) continue;
      let idx3 = -100000;
      let level = '';
      data.jobs.forEach((job) => {
        const idx = text.indexOf(job);
        if (idx != -1 && Math.abs(idx2 - idx3) > Math.abs(idx2 - idx)) {
          idx3 = idx;
          level = job;
        }
      });
      if (idx3 < 0 || Math.abs(idx2 - idx3) > 30) continue;
      let href = $(container[i]).find('.b_tpcn a.tilk').attr('href');
      href = href.includes('http') ? href : window.location.origin + href;
      const gap = Math.abs(idx2 - idx3);
      //const start = idx2 > idx3 ? idx3 : idx2;
      const start = idx1 > idx2 ? (idx2 > idx3 ? idx3 : idx2) : idx1 > idx3 ? idx3 : idx1;
      //const end = idx2 > idx3 ? idx2 : idx3;
      const end = idx1 > idx2 ? (idx1 > idx3 ? idx1 : idx3) : idx2 > idx3 ? idx2 : idx3;
      const word = text
        .substring(start < 10 ? 0 : start - 10, end + 10)
        .replace(data.company, `<em>${data.company}</em>`)
        .replace(data.name, `<em>${data.name}</em>`)
        .replace(level, `<em>${level}</em>`);

      userList.push({
        from: 'biying',
        name: data.name,
        level: level,
        gap: gap,
        company: data.company,
        href: href,
        word: word
      });
    }
    return userList;
  }
};

$(() => {
  chrome.runtime.sendMessage({ type: 'searchready', from: 'biying' }, function (response) {
    if (response?.action == 'match') {
      setTimeout(() => {
        window.scrollTo({
          top: document.body.scrollHeight,
          behavior: 'smooth'
        });
      }, random(200, 400));
      //判断是不是结束
      if(!response?.data){
        return chrome.runtime.sendMessage({ type: 'closetab', from: 'biying' });
      }
      setTimeout(() => {
        utils.startMatch(response?.data);
      }, random(800, 1200));
    }
  });
});
